//go:generate goversioninfo
package main

/**
Note:程序描述和图标依赖于 go install github.com/josephspurrier/goversioninfo/cmd/goversioninfo@latest
*/

import (
	yaml2 "ez-starter/yaml"
	"flag"
	"gitee.com/dreamwood/ez"
	"gitee.com/dreamwood/ez/server"
	"github.com/getlantern/systray"
	"gopkg.in/yaml.v2"
	"os"
	"os/signal"
	"syscall"
)

var config string
var site string

var stops map[string][]map[string]interface{}

var root string

func main() {
	root, _ = os.Getwd()
	flag.StringVar(&config, "config", "start.yaml", "配置文件名")
	flag.StringVar(&site, "site", "", "项目key,默认所有项目")
	flag.Parse()
	file, e := os.ReadFile(config)
	if ez.PrintError(e) {
		return
	}
	anything := make(map[string][]map[string]interface{})
	e = yaml.Unmarshal(file, &anything)
	if ez.PrintError(e) {
		return
	}

	file, e = os.ReadFile("./stop.yaml")
	if ez.PrintError(e) {
		return
	}
	stops = make(map[string][]map[string]interface{})
	e = yaml.Unmarshal(file, &stops)
	if ez.PrintError(e) {
		return
	}

	yaml2.InitVar()
	for key, steps := range anything {
		if site != "" && site != key {
			continue
		}
		for _, program := range steps {
			for entry, params := range program {
				yaml2.PassTo(entry, params)
			}
		}
	}

	ez.S.Host = "127.0.0.1"
	ez.S.Port = 23085
	server.AddPreparer("CORS", func(operation *server.Operation) {
		operation.Output.Response.Header().Set("Access-Control-Allow-Origin", "*")
		operation.Output.Response.Header().Set("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token, a-auth-token, Authorization, x-auth-token")
		operation.Output.Response.Header().Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		operation.Output.Response.Header().Set("Access-Control-Allow-Credentials", "true")
		operation.Output.Response.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
		if operation.Input.Request.Method == "OPTIONS" {
			operation.Stop()
		}
	})

	server.Do(&server.Router{Url: "/heart"}, func(operation *server.Operation) {
		data := ez.M{}
		data["code"] = 2001
		data["message"] = "服务正在运行"
		data["data"] = ""
		operation.JsonOut(data)
	})

	go server.Run()
	systray.Run(OnReady, OnQuit)
}

func OnReady() {
	os.Chdir(root)
	ico, _ := os.ReadFile("./ico.ico")
	//这里可以设置托盘图标但是不能设置程序图标
	systray.SetIcon(ico)
	mQuit := systray.AddMenuItem("退出", "退出程序")

	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, syscall.SIGTERM, syscall.SIGINT)

	for {
		select {
		case <-mQuit.ClickedCh:
			systray.Quit()
		case <-sigc:
			systray.Quit()
		}
	}
}
func OnQuit() {

	yaml2.InitVar()
	for key, steps := range stops {
		if site != "" && site != key {
			continue
		}
		for _, program := range steps {
			for entry, params := range program {
				yaml2.PassTo(entry, params)
			}
		}
	}
}
